import React, { Component } from 'react';
import { Menu } from 'antd';
import { Link, withRouter, RouteComponentProps } from 'react-router-dom';
import History from 'history';
import './index.scss';

const { SubMenu } = Menu;

class NavigationBar extends Component<RouteComponentProps> {

    state = {
        current: []
    }

    listenHistoryChange = () => {
        this.unlistenHistoryChange = this.props.history.listen(this.changeMeunByLocation);
    }

    unlistenHistoryChange = () => { }

    componentDidMount() {
        this.changeMeunByLocation(this.props.location);
        this.listenHistoryChange();
    }

    componentWillUnmount() {
        this.unlistenHistoryChange();
    }

    /**
     * 通过 location.pathname 改变导航栏激活状态 
     * @param location History.Location
     */
    changeMeunByLocation = (location: History.Location) => {
        let current;
        if (location.pathname === '/' || location.pathname === '') {
            current = ['home'];
        } else {
            current = location.pathname.split('/').slice(1);
        }
        this.setState({
            current: current.length > 0 ? current : ['home']
        });
    }

    render() {
        return (
            <Menu
                className="navagition-bar"
                mode="horizontal"
                selectedKeys={this.state.current}
            >
                <Menu.Item key="home">
                    <Link to="/">首页</Link>
                </Menu.Item>

                <SubMenu key="specialTools" title="专用工具">
                    <Menu.Item key="attendance">
                        <Link to="/specialTools/attendance">考勤处理</Link>
                    </Menu.Item>
                </SubMenu>
            </Menu >
        );
    }
}
export default withRouter(NavigationBar);